package cn.steel.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.steel.domain.entity.Notification;
import cn.steel.domain.vo.NotificationVo;
import cn.steel.mapper.NotificationMapper;
import cn.steel.service.NotificationService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class NotificationServiceImpl implements NotificationService {

    private final NotificationMapper notificationMapper;

    @Override
    public Page<NotificationVo> getNotificationsPaginated(Long userId, int page, int size) {
        PageHelper.startPage(page, size);
        List<Notification> notifications = notificationMapper.findNotificationsByUserId(userId);
        List<NotificationVo> notificationVos = notifications.stream().map(n -> {
            NotificationVo vo = new NotificationVo();
            BeanUtil.copyProperties(n, vo);
            vo.setTypeText(getTypeText(n.getType()));
            vo.setReadText(n.getIsRead() ? "已读" : "未读");
            return vo;
        }).collect(Collectors.toList());

        Page<NotificationVo> pageResult = new Page<>();
        BeanUtil.copyProperties(notifications, pageResult);
        pageResult.addAll(notificationVos);
        return pageResult;
    }

    @Override
    @Transactional
    public void markAsRead(Long id, Long userId) {
        Notification notification = notificationMapper.findById(id);
        if (notification == null || !notification.getUserId().equals(userId)) {
            throw new IllegalArgumentException("通知不存在或无权限");
        }
        notification.setIsRead(true);
        notificationMapper.updateNotification(notification);
        log.info("Marked notification as read: id={}, userId={}", id, userId);
    }

    @Override
    @Transactional
    public void deleteNotification(Long id, Long userId) {
        Notification notification = notificationMapper.findById(id);
        if (notification == null || !notification.getUserId().equals(userId)) {
            throw new IllegalArgumentException("通知不存在或无权限");
        }
        notificationMapper.deleteNotification(id);
        log.info("Deleted notification: id={}, userId={}", id, userId);
    }

    private String getTypeText(String type) {
        return switch (type) {
            case "SYSTEM" -> "系统消息";
            case "ORDER" -> "订单消息";
            case "PRICE" -> "价格变动";
            default -> "未知";
        };
    }
}